package com.jgdt.demo.api;
import com.librariy.net.HttpResponse;
import com.librariy.util.Log;
import com.jgdt.demo.AppContext;
import com.jgdt.demo.AppData;
import com.librariy.json.JsonObject;
import com.librariy.net.HttpClient;
import com.librariy.util.UIHelper;
import android.text.TextUtils;
import android.util.Base64;

/**
 * 访问控制器
 *
 * @author luchyu
 */
public class AccessCtrl {
    public static String TAG = "AccessCtrl";
    public static String SharedPreferencesKEY = "access.cache";

    public enum Key {autoLogin, identity, password, userName, name, role, exp, userId, token, deptNum, deptName}

    private static JsonObject mCache = null;
    private static String mToken = null;

    public static String get(Key mKey) {
        if (mCache == null) {
            mCache = new JsonObject(AppData.getString(SharedPreferencesKEY, ""));
        }
        return mCache.optString(mKey, "");
    }

    public static String getToken() {
        return TextUtils.isEmpty(mToken) ? "" : mToken;
    }

    public static String getUserName() {
        return AccessCtrl.get(Key.userName);
    }

    public static String getName() {
        return AccessCtrl.get(Key.name);
    }

    public static String getUserId() {
        return AccessCtrl.get(Key.userId);
    }

    public static String getIdentity() {
        return AccessCtrl.get(Key.identity);
    }

    public static String getPassword() {
        return AccessCtrl.get(Key.password);
    }

    public static String getDeptNum() {
        return AccessCtrl.get(Key.deptNum);
    }

    public static String getDeptName() {
        return AccessCtrl.get(Key.deptName);
    }

    public static boolean isAutoLogin() {
        return "true".equalsIgnoreCase(AccessCtrl.get(Key.autoLogin));
    }

    public static boolean isLogin() {
        return !TextUtils.isEmpty(getToken());
    }

    /**
     * 本地退出（清除本地登录信息及缓存）
     */
    public static void reset(boolean clearCache) {
        mCache = null;
        mToken = null;
        SysInterface.reset();
        //设置当前用户ID为推送别名
        if (!clearCache) return;
        AppData.putString(SharedPreferencesKEY, "{}");
        AppContext.setPushAlias(null);
    }

    public static JsonObject parserToken(String token) {
        try {
            String a1[] = token.split("[.]");
            String a2 = (a1 == null || a1.length != 3) ? "{}" : a1[1];
            a2 = new String(Base64.decode(a2, Base64.NO_WRAP));
            JsonObject re = new JsonObject(a2);
            if (re.optString(Key.userId, "").equals("")) {
                throw new Exception("Token Error!");
            }
            return re;
        } catch (Exception e) {
            Log.e(TAG, "parserToken", e);
            return null;
        }
    }

    /**
     * 完全退出（通知服务器退出，并清除本地缓存）
     */
    public static void logout(final LoginResponse callback) {
        JsonRequest request = new JsonRequest(JsonRequest.Method.POST_JSON, "/UsersCenter/LogOut");
        HttpClient.request(request, new HttpResponse() {
            @Override
            public void onCompleted(int responseCode, String responseText) {
                if (responseCode == 200) {
                    callback.onCompleted(true, "退出成功");
                } else {
                    callback.onCompleted(false, responseText);
                }
            }
        });
    }

    public static void login(final String mAccount, final String mPassword, final LoginResponse callback) {
        if (AccessCtrl.isLogin()) {
            callback.onCompleted(true, "已登陆！");
            return;
        }
        if (TextUtils.isEmpty(mAccount)) {
            callback.onCompleted(false, "用户名不能为空！");
            return;
        }
        if (TextUtils.isEmpty(mPassword)) {
            callback.onCompleted(false, "密码不能为空！");
            return;
        }
        JsonRequest request = new JsonRequest(JsonRequest.Method.POST_JSON, "/auth/login");
        request.addBodyField("username", mAccount);
        request.addBodyField("password", mPassword);
        HttpClient.request(request, new JsonResponse() {
            @Override
            public void onCompleted(boolean success, int code, String message, JsonObject originObject) {
                // 响应结果为false
                // 460：账号、密码错误；465：密码错误多次
                if (!success) {
                    Log.e(TAG, "resultCode:" + code);
                    if (message.equals("请求出错")) {
                        message = "登录失败";
                    } else if (message.equals("非法参数错误")) {
                        message = "账号密码错误";
                    }
                    callback.onCompleted(false, message);
                    return;
                }
                JsonObject userInfo=originObject.optJsonObject("data",new JsonObject());
                if (userInfo == null) {
                    UIHelper.dismissDialog();
                    Log.e(TAG, "登录接口 - 用户信息为空");
                    callback.onCompleted(false, "登录失败，请稍后重试！");
                    return;
                }
                SysInterface.reset();
                mToken=userInfo.optString("token","");
                JsonObject loginInfo=new JsonObject();
                loginInfo.put(Key.identity, mAccount);
                loginInfo.put(Key.password, mPassword);
                loginInfo.put(Key.userName, userInfo.optString("userName",""));
                getUserInfoRequest(loginInfo,callback);
            }
        });
    }

    public static interface LoginResponse {
        public void onCompleted(boolean isSuccess, String msg);
    }

    /**
     * 获取UserId
     */
    private static void getUserInfoRequest(final JsonObject loginInfo, final LoginResponse callback) {
        JsonRequest request = new JsonRequest(JsonRequest.Method.GET, "/base/user/getUser");
        //UIHelper.showDialog();
        HttpClient.request(request, new JsonResponse() {
            @Override
            public void onCompleted(boolean success, int code, String message, JsonObject originObject) {
                UIHelper.dismissDialog();
                if (!success) {
                    mToken=null;
                    Log.e(TAG, "获取用户Id接口 - 错误：" + message);
                    callback.onCompleted(false, message);
                    return;
                }
                // 获取UserId
                JsonObject data = originObject.optJsonObject(ResponseKey.data, new JsonObject());
                mCache = new JsonObject();
                //保存登录信息
                mCache.putAll(loginInfo);
                //保存getUser接口信息
                mCache.put(Key.userId, data.optString(Key.userId, ""));
                mCache.put(Key.name, data.optString(Key.name, ""));
                mCache.put(Key.deptNum, data.optString(Key.deptNum, ""));
                mCache.put(Key.deptName, data.optString(Key.deptName, ""));
                //保存缓存
                AppData.putString(SharedPreferencesKEY, mCache.toString());
                //设置当前用户ID为推送别名
                AppContext.setPushAlias(AccessCtrl.getUserId());
                callback.onCompleted(true, "登录成功");
                Log.d(TAG, "登录成功");
            }
        });
    }
}
